<template>
  <div class="user-list-container">
    <!-- 搜索区域 -->
    <div class="search-area mb-4 flex items-center gap-4">
      <el-input
        v-model="searchForm.userName"
        :placeholder="t('userList.search.userName')"
        style="width: 200px"
        clearable
        @clear="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>

      <el-select
        v-model="searchForm.attentionType"
        :placeholder="t('userList.search.attentionType')"
        clearable
        style="width: 200px"
      >
        <el-option
          v-for="item in attentionTypeList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>

      <el-select
        v-model="searchForm.roleCode"
        :placeholder="t('userList.search.roleCode')"
        clearable
        style="width: 200px"
      >
        <el-option
          v-for="item in dictData.userRoleList"
          :key="item.code"
          :label="item.name"
          :value="item.code"
        />
      </el-select>

      <el-date-picker
        v-model="searchForm.reportTimeRange"
        type="daterange"
        :start-placeholder="t('userList.search.reportTimeRange')"
        :end-placeholder="t('userList.search.reportEndDate')"
        value-format="x"
        style="width: 200px"
      />

      <el-date-picker
        v-model="searchForm.followUpTimeRange"
        type="daterange"
        :start-placeholder="t('userList.search.followUpTimeRange')"
        :end-placeholder="t('userList.search.followUpEndDate')"
        value-format="x"
        style="width: 200px"
      />

      <el-select
        v-model="searchForm.riskLevelId"
        :placeholder="t('userList.search.riskLevel')"
        clearable
        style="width: 200px"
      >
        <el-option
          v-for="item in dictData.riskLevelList || []"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>

      <el-select
        v-model="searchForm.healthCategoryId"
        :placeholder="t('userList.search.healthCategory')"
        clearable
        style="width: 200px"
      >
        <el-option
          v-for="item in dictData.healthCategoryList || []"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <el-select
        v-model="searchForm.healthManagerId"
        :placeholder="t('userList.search.healthManager')"
        clearable
        style="width: 200px"
      >
        <el-option
          v-for="item in healthManagerOptions"
          :key="item.userId"
          :label="item.userName"
          :value="item.userId"
        />
      </el-select>
      <el-button @click="handleReset">
        {{ t("userList.search.resetButton") }}
      </el-button>
      <el-button type="primary" @click="handleSearch">
        {{ t("userList.search.searchButton") }}
      </el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      stripe
      :element-loading-text="t('userList.table.loading')"
      :row-height="44"
      class="custom-table"
    >
      <el-table-column prop="userName" :label="t('userList.table.userInfo')">
        <template #default="{ row }">
          <div>{{ row.userId }}</div>
          <div class="user-role">{{ row.userName }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="userRole" :label="t('userList.table.role')">
        <template #default="{ row }">
          <div>{{ row.userRole }}</div>
        </template>
      </el-table-column>
      <el-table-column
        prop="gender"
        :label="t('userList.table.gender')"
        width="80"
      />
      <el-table-column :label="t('userList.table.attentionLevel')" width="150">
        <template #default="{ row }">
          <!-- <el-rate v-model="row.attentionType" :max="5" disabled /> -->
          <EditableRate
            v-model="row.attentionType"
            :data-type="4"
            :data-id="row.userId"
          />
        </template>
      </el-table-column>
      <el-table-column
        :label="t('userList.table.healthManager')"
        min-width="120"
      >
        <template #default="{ row }">
          <template v-if="row.healthManagerId">
            <div class="flex items-center">
              <span>{{ row.healthManagerName }}</span>
              <el-icon
                class="ml-2 cursor-pointer text-primary"
                @click="handleEditHealthManager(row)"
              >
                <Edit />
              </el-icon>
            </div>
          </template>
          <template v-else>
            <div class="empty-flag">
              {{ t("userList.table.noHealthManager") }}
            </div>
            <div class="assign-manager" @click="handleEditHealthManager(row)">
              {{ t("userList.table.assignHealthManager") }}
            </div>
          </template>
        </template>
      </el-table-column>

      <el-table-column
        prop="doctorName"
        :label="t('userList.table.doctor')"
        min-width="120"
      />
      <el-table-column :label="t('userList.table.riskLevel')" width="120">
        <template #default="{ row }">
          <span
            :class="{
              'riskLevel-tag': true,
              'riskLevel-tag--sub':
                row.riskLevel === t('userList.riskLevels.good'),
              'riskLevel-tag--normal':
                row.riskLevel === t('userList.riskLevels.mild'),
              'riskLevel-tag--chronic':
                row.riskLevel === t('userList.riskLevels.high') ||
                row.riskLevel === t('userList.riskLevels.moderateHigh') ||
                row.riskLevel === t('userList.riskLevels.moderate')
            }"
          >
            {{ row.riskLevel }}
          </span>
        </template>
      </el-table-column>
      <el-table-column :label="t('userList.table.healthCategory')" width="120">
        <template #default="{ row }">
          <span
            :class="{
              'health-tag': true,
              'health-tag--sub':
                row.healthCategory === t('userList.healthCategories.subHealth'),
              'health-tag--normal':
                row.healthCategory === t('userList.healthCategories.healthy'),
              'health-tag--chronic':
                row.healthCategory === t('userList.healthCategories.chronic'),
              'health-tag--doctor':
                row.healthCategory ===
                  t('userList.healthCategories.outpatient') ||
                row.healthCategory === t('userList.healthCategories.emergency'),
              'health-tag--hospital':
                row.healthCategory === t('userList.healthCategories.inpatient')
            }"
          >
            {{ row.healthCategory }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        prop="reportCount"
        :label="t('userList.table.reportCount')"
        width="100"
      >
        <template #default="{ row }">
          <span style="color: #2dafff">{{ row.reportCount }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="lastReportTime"
        :label="t('userList.table.lastCheckTime')"
        min-width="120"
        :formatter="formatDate"
      />
      <el-table-column
        prop="lastFollowUpTime"
        :label="t('userList.table.lastFollowUpTime')"
        min-width="120"
        :formatter="formatDate"
      />
      <el-table-column
        :label="t('userList.table.actions')"
        fixed="right"
        width="140"
        align="left"
      >
        <template #default="{ row }">
          <div class="flex flex-col gap-1 items-start">
            <el-button
              v-if="row.myServiceUser"
              type="primary"
              link
              @click="handleUploadReport(row)"
            >
              {{ t("userList.actions.uploadReport") }}
            </el-button>
            <el-button
              v-if="row.myServiceUser"
              type="primary"
              link
              @click="handleViewLastReport(row)"
            >
              {{ t("userList.actions.viewLastReport") }}
            </el-button>
            <el-button
              v-if="row.myServiceUser"
              type="primary"
              link
              @click="handleViewArchive(row)"
            >
              {{ t("userList.actions.viewArchive") }}
            </el-button>
            <el-button
              v-if="row.myServiceUser"
              type="primary"
              link
              @click="handleAddPlan(row)"
            >
              {{ t("userList.actions.addTaskPlan") }}
            </el-button>
            <el-button
              v-if="!row.myServiceUser"
              type="primary"
              link
              @click="handleApplyPermission(row)"
            >
              {{ t("userList.actions.applyPermission") }}
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="flex justify-end mt-4">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 修改健管师抽屉 -->
    <el-drawer
      v-model="healthManagerDialog.visible"
      :title="t('userList.healthManagerDialog.title')"
      size="500px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <div class="drawer-content">
        <p class="drawer-tip">
          {{
            t("userList.healthManagerDialog.tip", {
              userName: healthManagerDialog.currentRow?.userName
            })
          }}
        </p>
        <div class="form-item">
          <span class="label">{{ t("userList.search.healthManager") }}</span>
          <el-select
            v-model="healthManagerDialog.form.healthManagerId"
            :placeholder="t('userList.healthManagerDialog.selectHealthManager')"
            style="width: 240px"
            :loading="healthManagerDialog.loading"
          >
            <el-option
              v-for="item in healthManagerOptions"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            />
          </el-select>
        </div>
      </div>
      <template #footer>
        <div class="drawer-footer">
          <el-button
            type="primary"
            class="w-full"
            :loading="healthManagerDialog.submitting"
            @click="handleConfirmHealthManager"
          >
            {{ t("userList.healthManagerDialog.assign") }}
          </el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 任务计划弹窗 -->
    <follow-dialog
      v-model:visible="dialogVisible"
      :mode="dialogMode"
      :task-data="taskData"
      @submit="handleTaskSubmit"
    />
  </div>
</template>

<script lang="ts" setup>
import { followApi } from "@/api/follow";
import { reportApi } from "@/api/report-api";
import { ReportSearchConditionVO } from "@/api/types";
import type { UserSearchByDoctorVO } from "@/api/userList";
import { userListApi } from "@/api/userList";
import { attentionTypeList as commonAttentionTypeList } from "@/utils/tools";
import FollowDialog from "@/views/followUpPlan/components/followDialog.vue";
import { Edit, Search } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import { ElMessage } from "element-plus";
import { onMounted, reactive, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
const { t } = useI18n();
const router = useRouter();
const dialogVisible = ref(false);
const dictData = ref<ReportSearchConditionVO>({});
let dialogMode = ref("");
// 搜索表单数据
const searchForm = reactive({
  userName: "",
  attentionType: null,
  roleCode: "",
  reportTimeRange: [],
  followUpTimeRange: [],
  riskLevelId: null,
  healthCategoryId: null,
  healthManagerId: null
});

// 表格数据
const loading = ref(false);
const taskData = ref({});
const tableData = ref<UserSearchByDoctorVO[]>([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 选项数据
const attentionTypeList = ref(commonAttentionTypeList);

const roleOptions = [
  { value: "HIGH_RISK", label: t("userList.roleOptions.highRisk") },
  { value: "NORMAL", label: t("userList.roleOptions.normal") }
];

const healthManagerOptions = ref<any[]>([]);

// 健管师抽屉数据
const healthManagerDialog = reactive({
  visible: false,
  title: t("userList.healthManagerDialog.title"),
  loading: false,
  submitting: false,
  form: {
    userId: null as number | null,
    healthManagerId: null as number | null,
    healthCategoryId: null as number | null,
    familyId: null as number | null
  },
  currentRow: null as UserSearchByDoctorVO | null
});

// 打开修改健管师抽屉
const handleEditHealthManager = (row: UserSearchByDoctorVO) => {
  healthManagerDialog.currentRow = row;
  healthManagerDialog.form.userId = row.userId || null;
  healthManagerDialog.form.healthCategoryId = row.healthCategoryId || null;
  healthManagerDialog.form.familyId = row.familyId || null;
  healthManagerDialog.form.healthManagerId = row.healthManagerId || null;
  healthManagerDialog.visible = true;
  // handleConfirmHealthManager();
};

// 确认修改健管师
const handleConfirmHealthManager = async () => {
  try {
    if (
      !healthManagerDialog.form.userId ||
      !healthManagerDialog.form.healthManagerId
    ) {
      ElMessage.warning(t("userList.messages.selectHealthManagerWarning"));
      return;
    }

    healthManagerDialog.submitting = true;

    // 调用分配健管师接口
    const res = await userListApi.getFollowUpPlanDoctorAssignHealthManager({
      userId: healthManagerDialog.form.userId,
      healthCategoryId: healthManagerDialog.form.healthManagerId,
      // HealthCategoryId: healthManagerDialog.form.healthCategoryId || 0,
      familyId: healthManagerDialog.form.familyId || 0
    });

    // // 更新表格数据
    // if (healthManagerDialog.currentRow) {
    //   const selectedManager = healthManagerOptions.value.find(
    //     item => item.id === healthManagerDialog.form.healthManagerId
    //   );
    //   if (selectedManager) {
    //     healthManagerDialog.currentRow.healthManagerId = selectedManager.id;
    //     healthManagerDialog.currentRow.healthManagerName = selectedManager.name;
    //   }
    // }
    if (res.data.result) {
      ElMessage.success(t("userList.messages.assignSuccess"));
    } else {
      ElMessage.error(res.data.message);
    }

    // ElMessage.success(t("userList.messages.assignSuccess"));
    healthManagerDialog.visible = false;
  } catch (error) {
    console.error(t("userList.messages.assignHealthManagerFailed"), error);
    ElMessage.error(t("userList.messages.assignFailed"));
  } finally {
    healthManagerDialog.submitting = false;
  }
};

// 日期格式化
const formatDate = (row: any, column: any) => {
  const value = row[column.property];
  return value ? dayjs(value).format("YYYY-MM-DD") : "";
};
// 处理任务提交
const handleTaskSubmit = formData => {
  console.log(t("userList.messages.submitFormData"), formData);
  // TODO: 根据是否有currentTask.value来判断是创建还是编辑
  // 这里可以调用API进行保存
  dialogVisible.value = false;
  ElMessage.success(t("userList.messages.createSuccess"));
  fetchTableData(); // 刷新任务列表
};
// 获取表格数据
const fetchTableData = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      userName: searchForm.userName,
      attentionType: searchForm.attentionType,
      roleCode: searchForm.roleCode,
      riskLevelId: searchForm.riskLevelId,
      healthCategoryId: searchForm.healthCategoryId,
      healthManagerId: searchForm.healthManagerId,
      reportStartTime: searchForm.reportTimeRange[0],
      reportEndTime: searchForm.reportTimeRange[1],
      followUpStartTime: searchForm.followUpTimeRange[0],
      followUpEndTime: searchForm.followUpTimeRange[1]
    };

    const res = await userListApi.getFollowUpPlanTaskSearchApi(params);
    if (res.data) {
      tableData.value = res.data.list || [];
      total.value = res.data.total || 0;
    }
  } catch (error) {
    console.error(t("userList.messages.dataFetchFailed"), error);
    ElMessage.error(t("userList.messages.dataFetchFailed"));
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = async () => {
  try {
    currentPage.value = 1;
    await fetchTableData();
  } catch (error) {
    console.error(t("userList.messages.searchFailed"), error);
    ElMessage.error(t("userList.messages.searchFailed"));
  }
};

// 重置处理
const handleReset = async () => {
  Object.keys(searchForm).forEach(key => {
    if (key !== "pageNum" && key !== "pageSize") {
      searchForm[key] = "";
    }
  });
  currentPage.value = 1;

  try {
    await fetchTableData();
  } catch (error) {
    console.error(t("userList.messages.resetFailed"), error);
    ElMessage.error(t("userList.messages.resetFailed"));
  }
};

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  fetchTableData();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  fetchTableData();
};

// 操作按钮处理函数
const handleUploadReport = (row: UserSearchByDoctorVO) => {
  try {
    // console.log(t("userList.actions.uploadReport"), row);
    // ElMessage.info(t("userList.messages.uploadReportDev"));
    router.push({
      path: "/addReport/index"
    });
  } catch (error) {
    console.error(t("userList.messages.uploadReportFailed"), error);
    ElMessage.error(t("userList.messages.uploadReportFailed"));
  }
};

// 处理view-report消息的具体逻辑
const handleViewLastReport = async (row: any) => {
  try {
    // 从消息中获取userId
    const userId = row.userId;

    // 调用API获取用户最近一次报告
    const response = await reportApi.queryUserLatestReport({
      reportUserId: userId,
      reportType: 1
    });

    if (response.code === 0 && response.data) {
      const reportId = response.data.reportId;

      if (reportId) {
        // 路由跳转到报告详情页面
        router.push({
          path: "/report/detail",
          query: { reportId, mode: "view" }
        });
      } else {
        ElMessage.warning("该用户暂无报告数据");
      }
    } else {
      ElMessage.error(response.message || "获取报告数据失败");
    }
  } catch (error) {
    console.error("处理view-report失败:", error);
    ElMessage.error("获取报告数据失败");
  }
};

const handleViewArchive = (row: UserSearchByDoctorVO) => {
  try {
    if (!row?.userId) {
      ElMessage.warning(t("userList.messages.invalidUserId"));
      return;
    }
    router.push({
      path: "/healthRecords/detail",
      query: {
        userId: row.userId
      }
    });
  } catch (error) {
    console.error(t("userList.messages.viewArchiveFailed"), error);
    ElMessage.error(t("userList.messages.viewArchiveFailed"));
  }
};

const handleAddPlan = (row: UserSearchByDoctorVO) => {
  dialogMode.value = "create";
  dialogVisible.value = true;
  taskData.value = row;
};

const handleApplyPermission = (row: UserSearchByDoctorVO) => {
  console.log(t("userList.actions.applyPermission"), row);
  ElMessage.info(t("userList.messages.applyPermissionDev"));
};

// 获取字典数据
async function queryDictionaryData() {
  try {
    const response = await reportApi.queryReportDict();
    if (response?.data) {
      dictData.value = response.data;
    }
  } catch (err) {
    console.error(t("userList.messages.fetchDictDataFailed"), err);
    ElMessage.error(t("userList.messages.fetchDictDataFailed"));
  }
}
// 获取健管师列表
const fetchHealthManagerList = async () => {
  try {
    const res = await followApi.getFollowUpPlanDoctorHealthManager();
    if (res.data) {
      healthManagerOptions.value = res.data;
    }
  } catch (error) {
    console.error(t("userList.messages.fetchHealthManagerFailed"), error);
    ElMessage.error(t("userList.messages.fetchHealthManagerFailed"));
  }
};

onMounted(() => {
  fetchTableData();
  queryDictionaryData();
  fetchHealthManagerList();
});
</script>

<style lang="scss">
.user-list-container {
  background-color: #fff;
  border-radius: 12px;
  padding: 24px;

  // 自定义表格样式
  .custom-table {
    // 调整单元格内边距
    .el-table__cell {
      padding: 4px 0;
    }

    // 调整操作列按钮间距
    .flex-col {
      gap: 2px !important;
    }

    // 调整用户信息列的样式
    .user-role {
      margin-top: 2px;
    }

    // 调整按钮的内边距
    .el-button.el-button--primary.is-link {
      padding: 4px 0;
      height: auto;
      line-height: 1;
    }
  }

  .el-drawer__header {
    padding: 16px 20px;
    border-bottom: 1px solid #e4e7ed;
    color: #333;
    margin-bottom: 0;
    .el-drawer__title {
      font-size: 16px;
      font-weight: 500;
    }
  }
  .el-button + .el-button {
    margin: 0;
  }
  .search-area {
    margin: 0 0 16px;
    border-bottom: 1px solid #ebeef5;
    padding-bottom: 16px;
    flex-wrap: wrap;
  }

  .user-role {
    font-size: 12px;
    color: #333;
    margin-top: 4px;
  }

  .empty-flag {
    font-size: 12px;
    color: #999;
  }

  .assign-manager {
    font-size: 12px;
    color: #409eff;
    cursor: pointer;
    margin-top: 4px;

    &:hover {
      color: #66b1ff;
    }
  }

  .text-primary {
    color: #409eff;
    &:hover {
      color: #66b1ff;
    }
  }

  .riskLevel-tag,
  .health-tag {
    display: inline-block;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 12px;
  }

  .riskLevel-tag {
    font-weight: bold;
  }

  .health-tag {
    font-weight: bold;
  }

  .drawer-content {
    padding: 0 20px;

    .drawer-tip {
      margin-bottom: 20px;
      color: #666;
      font-size: 14px;
    }

    .form-item {
      display: flex;
      align-items: center;
      margin-bottom: 20px;

      .label {
        width: 80px;
        color: #333;
      }
    }
  }

  .drawer-footer {
    padding: 10px 20px;
    text-align: right;
  }
}
</style>
